前兩天,我們知道了何謂 Component 、 Component 如何撰寫與 React 開發邏輯。而今天我們要進入 React 重頭戲,資料傳遞。我們在開始前,我們必須要有一個觀念,不論是 Vue、 React 基本上框架現在都是走一個單向資料流概念,強調資料 immutable 特性。有了這些基本概念後,我們就開始今天的介紹吧!
資料由父層往下傳遞時都會透過 Props 屬性來傳遞給子元素。而在實務上時,我們通常會搭配 React Hooks 的 useState 來做資料狀態紀錄!我們先來簡單看個例子吧!
import ExpenseItem from './components/expense'; //引入 ExpenseItem 元件
function Demo(){
const expense = [
{
dollar:1000,
keeper:Andy
},
{
dollar:20000,
keeper:Mom
}
]
return(
<ExpenseItem attribute={expense[0].dollar}/>
)
}
元件中我們可以透過自定義 attribute 向引入 Component 傳遞,如上面我透過自定義 attribute。Props 概念有點像 function 在傳遞參數,差異僅在於 props 資料是單向流不能修改。而元件在接受外部資料時只會接受到一個物件。